package com.medica.ledproject.common;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mysql.cj.log.Log;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

/**
 * @author xiaona
 * @date 2024/6/25
 * @description TODO
 */
@Slf4j
public class HttpClientUtil {
    public static String basicUrl="q";
    //token验证
    public static String Authorization="";
    //登录
    public  static String logins=basicUrl+"/pbx/auth/login";
    //上传音乐
    public  static String uploadMusic=basicUrl+"/ginapi/plugin-storage/object";
    //获取音乐列表
    public  static String getMusicList=basicUrl+"/ginapi/plugin-storage/object";
    //添加播放列表
    public  static String addPalyList=basicUrl+"/ginapi/plugin-broadcast/play-list";
    //获取播放列表
    public  static String getPalyList=basicUrl+"/ginapi/plugin-broadcast/play-list";
    //删除音乐
    public  static String delMusic=basicUrl+"/ginapi/plugin-storage/object-bulk-delete";
    //播放音乐
    public  static String playMusic=basicUrl+"/ginapi/plugin-broadcast/play-task";
    //获取分机列表
    public  static String getPhoneList=basicUrl+"/ginapi/plugin-pbx/extensionall";
    //播放列表删除
    public  static String delPlay=basicUrl+"/ginapi/plugin-broadcast/play-list-bulk-delete";
    //删除任务
    public  static String delTask=basicUrl+"/ginapi/plugin-broadcast/play-task/c1568112-5292-49e5-aa41-4e7d4ab5bf1c";
    //获取任务列表
    public  static String getTaskList=basicUrl+"/ginapi/plugin-broadcast/play-task";

    /**
     * 话务台登录
     * @param username test
     * @param password admin
     */
    public static JSONObject loginS(String username,String password) {
        JSONObject parm = new JSONObject();
        parm.put("username", username);
        parm.put("password", password);
        //获取登录信息
        JSONObject data = post(logins, parm, Authorization);
        if (data.getInteger("code") == 0) {
            Authorization = data.getString("data");
        }
        return data;
    }

    /**
     * 上传音乐
     * @param file
     * @param Authorization
     * @return
     */
    public static JSONObject uploadMusic( MultipartFile file,String Authorization){
        boolean isLogin=false;
        JSONObject data = new JSONObject();
        InputStream fileInputStream = null;
        try {
            fileInputStream = file.getInputStream();
            data = upload(uploadMusic, fileInputStream, Authorization, "file", file.getOriginalFilename());
            if (data!=null&&data.getInteger("code") == 0) {
                log.info("上传文件返回："+data.toJSONString());
                log.info("上传音乐成功");
            } else {
                log.info("上传音乐失败");
            }
        } catch (Exception e) {
            log.error("上传音乐失败", e);
        }

        return data;

    }
    /**
     * 获取音乐列表
     * @param Authorization
     * @param page
     * @param pageSize
     * @return
     */
    public static JSONObject getMusicList(String Authorization,int page,int pageSize){
        //获取音乐列表
        String parms="?page="+page+"&limit="+pageSize;
        JSONObject data = gets(getMusicList, Authorization,parms);
        if(data!=null) {
            log.info("获取音乐列表参数：" + getMusicList + "获取音乐列表返回信息：" + data.toJSONString());
        }
        return data;
    }
    /**
     * 删除音乐列表
     * @param Authorization
     * @param ids [1,2,8]
     * @return
     */
    public static JSONObject delMusic(String Authorization,String ids){
        //删除播放列表
        JSONObject data = post1(delMusic,JSONArray.parseArray(ids), Authorization);
        if(data!=null) {
            log.info("删除音乐列表：" + delMusic +ids+ "删除音乐列表返回信息：" + data.toJSONString());
        }
        return data;
    }
    /**
     * 获取分机列表
     * @param Authorization
     * @param page
     * @param pageSize
     * @return
     */
    public static JSONObject getPhoneList(String Authorization,int page,int pageSize){
        //获取音乐列表
        String parms="?page="+page+"&limit="+pageSize;
        JSONObject data = gets(getPhoneList, Authorization,parms);
        if(data!=null) {
            log.info("获取分机列表参数：" + getPalyList + "获取分机列表返回信息：" + data.toJSONString());
        }
        return data;
    }
    /**
     * 添加音乐到播放列表
     * @param name
     * @param musicIds
     * @return
     */
    public static JSONObject addToPlay(String name,String musicIds,String Authorization) {
        JSONObject parm = new JSONObject();
        parm.put("name", name);
        parm.put("musicIds", JSONArray.parseArray(musicIds));
        //添加音乐到播放列表
        JSONObject data = post(addPalyList, parm, Authorization);
        if(data!=null) {
            log.info("添加音乐参数：" + addPalyList+parm.toJSONString() + "添加音乐返回信息：" + data.toJSONString());
        }
        return data;
    }

    /**
     * 获取播放列表
     * @param Authorization
     * @param page
     * @param pageSize
     * @return
     */
    public static JSONObject getPlayList(String Authorization,int page,int pageSize){
        //获取播放列表
        String parms="?page="+page+"&limit="+pageSize;
        JSONObject data = gets(getPalyList, Authorization,parms);
        if(data!=null) {
            log.info("获取播放列表参数：" + getPalyList + parms + "获取播放列表返回信息：" + data.toJSONString());
        }
        return data;
    }

    /**
     * 删除播放列表
     * @param Authorization
     * @param ids [1,2,8]
     * @return
     */
    public static JSONObject delPlayList(String Authorization,String ids){
        //删除播放列表
        JSONObject data = post1(delPlay,JSONArray.parseArray(ids), Authorization);
        if(data!=null) {
            log.info("删除播放列表参数：" + delPlay + ids + "删除播放列表返回信息：" + data.toJSONString());
        }
        return data;
    }

    /**
     * 播放音乐
     * @param Authorization
     * @param playListID 播放列表ID
     * @param cycleCount 循环次数
     * @param hangupAll 执行前是否挂断正在通话的设备
     * @return
     */
    public static JSONObject palyMusic(String Authorization,int playListID,int cycleCount,boolean hangupAll,String extensions){
        JSONObject parm=new JSONObject();
        parm.put("type", "now");
        parm.put("name", LocalDateTime.now().toString());
        //分机号码组
        JSONArray b=JSONArray.parseArray(extensions);
        parm.put("extensions",b);
        parm.put("playListID", playListID);
        parm.put("cycleCount", cycleCount);
        parm.put("hangupAll", hangupAll);
        JSONObject data=post(playMusic,parm,Authorization);
        if(data!=null) {
            log.info("获取播放列表参数：" + getPalyList + parm.toJSONString() + "获取播放列表返回信息：" + data.toJSONString());
        }
        return data;
    }
    /**
     * 获取任务列表
     * @param Authorization
     * @return
     */
    public static JSONObject getTaskList(String Authorization){
        JSONObject data = gets(getTaskList, Authorization,"");
        if(data!=null) {
            log.info("获取任务列表参数：" + getPalyList + "获取任务列表返回信息：" + data.toJSONString());
        }
        return data;
    }
    /**
     * 删除任务
     * @param Authorization
     * @return
     */
    public static JSONObject delTask(String Authorization,String uuid){
        JSONObject data = del(delTask,uuid, Authorization);
        if(data!=null) {
            log.info("删除任务参数：" + delTask + "删除任务列表返回信息：" + data.toJSONString());
        }
        return data;
    }
    /**
     * 上传文件
     * @param url
     * @param fileInputStream
     * @param Authorization
     * @param name
     * @param fileOriginalName
     * @return
     */
    public static  JSONObject upload(String url, InputStream fileInputStream, String Authorization, String name, String fileOriginalName){
        CloseableHttpClient client = null;
        try {
            client = new SSLClient();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } ;
        HttpPost post = new HttpPost(url);
        JSONObject jsonObject = null;
        try {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            //设置请求的编码格式
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            builder.setCharset(StandardCharsets.UTF_8);
            if (fileInputStream != null && name != null && fileOriginalName != null) {
//                builder.addBinaryBody(name, fileInputStream, ContentType.create(contentType),
//                        new String(fileOriginalName.getBytes()));
                builder.addBinaryBody(name, fileInputStream, ContentType.DEFAULT_BINARY,
                        new String(fileOriginalName.getBytes(),StandardCharsets.UTF_8));
            }
            post.setEntity(builder.build());
            //此处相当于在Authorization里头添加Bear token参数信息
            post.addHeader("Accept", "application/json");
            if(StringUtils.isNotBlank("Authorization")){
                post.addHeader("Authorization", Authorization);
            }
            HttpResponse res = client.execute(post);
            System.out.println(res.getStatusLine().getStatusCode());
            String response1 = EntityUtils.toString(res.getEntity(), StandardCharsets.UTF_8);
            System.out.println(response1);
            if (res.getStatusLine()
                    .getStatusCode() == HttpStatus.SC_OK) {
                // 返回json格式：
                jsonObject = JSONObject.parseObject(response1);
                System.out.println(jsonObject.toJSONString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return jsonObject;
    }
    /**
     * post请求
     * @param url
     * @param json
     * @param Authorization
     * @return
     */
    public static JSONObject post(String url, JSONObject json, String Authorization){
        CloseableHttpClient client = null;
        try {
            client = new SSLClient();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } ;
        HttpPost post = new HttpPost(url);
        JSONObject jsonObject = null;
        try {
            //创建请求体并添加数据
            StringEntity s = new StringEntity(json.toJSONString(), "utf-8");
            //此处相当于在header里头添加content-type等参数
            System.out.println(json.toJSONString());
            s.setContentType("application/json");
            s.setContentEncoding("UTF-8");
            post.setEntity(s);
            //此处相当于在Authorization里头添加Bear token参数信息
            post.addHeader("Accept", "application/json");
            post.addHeader("Content-Type", "application/json");
            if(StringUtils.isNotBlank("Authorization")){
                post.addHeader("Authorization", Authorization);
            }
            HttpResponse res = client.execute(post);
            String response1 = EntityUtils.toString(res.getEntity());
            System.out.println(response1);
            if (res.getStatusLine()
                    .getStatusCode() == HttpStatus.SC_OK) {
                // 返回json格式：
                jsonObject = JSONObject.parseObject(response1);
                System.out.println(jsonObject.toJSONString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return jsonObject;
    }
    /**
     * del请求
     * @param url
     * @param json
     * @param Authorization
     * @return
     */
    public static JSONObject del(String url, String parm, String Authorization){
        CloseableHttpClient client = null;
        try {
            client = new SSLClient();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } ;
        HttpDelete post = new HttpDelete(url+parm);
        JSONObject jsonObject = null;
        try {

            //此处相当于在Authorization里头添加Bear token参数信息
            post.addHeader("Accept", "application/json");
            post.addHeader("Content-Type", "application/json");
            if(StringUtils.isNotBlank("Authorization")){
                post.addHeader("Authorization", Authorization);
            }
            HttpResponse res = client.execute(post);
            String response1 = EntityUtils.toString(res.getEntity());
            System.out.println(response1);
            if (res.getStatusLine()
                    .getStatusCode() == HttpStatus.SC_OK) {
                // 返回json格式：
                jsonObject = JSONObject.parseObject(response1);
                System.out.println(jsonObject.toJSONString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return jsonObject;
    }
    /**
     * post请求
     * @param url
     * @param json
     * @param Authorization
     * @return
     */
    public static JSONObject post1(String url, JSONArray json, String Authorization){
        CloseableHttpClient client = null;
        try {
            client = new SSLClient();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } ;
        HttpPost post = new HttpPost(url);
        JSONObject jsonObject = null;
        try {
            //创建请求体并添加数据
            StringEntity s = new StringEntity(json.toJSONString(), "utf-8");
            //此处相当于在header里头添加content-type等参数
            System.out.println(json.toJSONString());
            s.setContentType("application/json");
            s.setContentEncoding("UTF-8");
            post.setEntity(s);
            //此处相当于在Authorization里头添加Bear token参数信息
            post.addHeader("Accept", "application/json");
            post.addHeader("Content-Type", "application/json");
            if(StringUtils.isNotBlank("Authorization")){
                post.addHeader("Authorization", Authorization);
            }
            HttpResponse res = client.execute(post);
            String response1 = EntityUtils.toString(res.getEntity());
            System.out.println(response1);
            if (res.getStatusLine()
                    .getStatusCode() == HttpStatus.SC_OK) {
                // 返回json格式：
                jsonObject = JSONObject.parseObject(response1);
                System.out.println(jsonObject.toJSONString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return jsonObject;
    }

    /**
     * get请求
     * @param url
     * @param Authorization token
     * @param parm
     * @return
     */
    public static  JSONObject gets(String url,String Authorization,String parm){
        CloseableHttpClient client = null;
        try {
            client = new SSLClient();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } ;
        HttpGet post = new HttpGet(url+parm);
        log.info("请求参数："+url+parm);
        JSONObject jsonObject = null;
        try {
            //此处相当于在Authorization里头添加Bear token参数信息
            // post.addHeader("Content-Type", "application/json");
            post.addHeader("Accept", "application/json");
            post.addHeader("Content-Type", "application/json");
            if(StringUtils.isNotBlank("Authorization")){
                post.addHeader("Authorization", Authorization);
            }
            HttpResponse res = client.execute(post);
            String response1 = EntityUtils.toString(res.getEntity());
            log.info("请求视频数据参数："+url+parm+"结果数据："+response1);
            if (res.getStatusLine()
                    .getStatusCode() == HttpStatus.SC_OK) {
                // 返回json格式：
                jsonObject = JSONObject.parseObject(response1);
                System.out.println(jsonObject.toJSONString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return jsonObject;
    }

    public static void main(String[] args) {
        loginS("test","admin");
    }
}


